package cn.element.io.nio.case2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.element.io.util.ByteBufferUtil.debugAll;

@Slf4j
public class MultiThreadServer {

    /**
     * 任务线程
     */
    public static class Worker implements Runnable {
        private Selector selector;
        private final String name;
        private final Queue<Runnable> queue = new ConcurrentLinkedQueue<>();
        private volatile boolean start = false;  

        public Worker(String name) {
            this.name = name;
        }

        /**
         * 初始化线程,和Selector
         */
        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                selector = Selector.open();
                Thread thread = new Thread(this, name);
                thread.start();
                start = true;
            }
            
            // 向队列添加了任务,但是这个任务并没有立即执行
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            
            selector.wakeup();  // 唤醒select方法
        }

        @Override
        public void run() {
            while (true) {  
                try {
                    selector.select();  // worker0
                    Runnable task = queue.poll();
                    
                    if (task != null) {  // 执行了sc.register()
                        task.run();
                    }
                    
                    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                    while (it.hasNext()) {
                        SelectionKey key = it.next();
                        it.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.debug("read... {}", channel.getRemoteAddress());
                            channel.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        
        ssc.bind(new InetSocketAddress(8888));
        
        // 1.创建固定数量的Worker,并初始化
        Worker[] workers = new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }

        AtomicInteger index = new AtomicInteger();
        
        while (true) {
            boss.select();
            Iterator<SelectionKey> it = boss.selectedKeys().iterator();
            
            while (it.hasNext()) {
                SelectionKey key = it.next();
                it.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected... {}", sc.getRemoteAddress());
                    // 2.关联selector
                    log.debug("before register... {}", sc.getRemoteAddress());
                    
                    // round robin轮询
                    workers[index.getAndIncrement() % workers.length].register(sc);
                    log.debug("after register... {}", sc.getRemoteAddress());
                }
            }
        }
    }
}
